package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmUpdateDataService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateVO;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.dynamic.crm.strategy.MainBusinessDynamicStrategy;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.parent.pojo.UpdateValidateReturnPojo;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicUpdateDTO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.ConsistencySyncProducer;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.service.CompetitorService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: yingjf
 * @date: 2022/8/22 09:20
 * @description: 竞争对手
 */
@Slf4j
@Service("competitorFormDataUpdateServiceImpl")
public class CompetitorFormDataUpdateServiceImpl extends AbstractCrmUpdateDataService {
    @Resource
    private ProModelService proModelService;
    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private UserHelp userHelp;
    @Resource
    private CompetitorService competitorService;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;
    @Resource
    private ConsistencySyncProducer consistencySyncProducer;

    @Override
    public void apiHook(FormDataUpdateDTO formDataUpdateDTO, UpdateVO updateVO, BeforeUpdateVO beforeUpdateVO) throws XbbException {
        // 第三方服务
        lowCodeExecuteService(formDataUpdateDTO, updateVO, beforeUpdateVO);
    }

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.COMPETITOR.getCode());
    }

    @Override
    public UpdateValidateReturnPojo analyticalData(FormDataUpdateDTO formDataUpdateDTO, ValidateDataDTO validateDataDTO, PaasFormDataEntity oldPaasFormDataEntity, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        UpdateValidateReturnPojo updateValidateReturnPojo = super.analyticalData(formDataUpdateDTO, validateDataDTO, oldPaasFormDataEntity, explainMap);

        formDataUpdateDTO.setVisbleDept(validateDataDTO.getVisbleDept());
        formDataUpdateDTO.setVisbleUser(validateDataDTO.getVisbleUser());
        return updateValidateReturnPojo;
    }

    @Override
    public UpdateVO update(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        try {
            String corpid = formDataUpdateDTO.getCorpid();
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            if ( Objects.equals(noApprovalRequired, 1) ) {
                CompetitorEntity competitorEntity = new CompetitorEntity();
                BeanUtil.copyProperties(paasFormDataEntity, competitorEntity);
                FormDataUtil.removeSystemData(competitorEntity.getData());
                Object richTextData = removeRichText(competitorEntity.getData());
                updateLine = competitorModel.update(competitorEntity);

                // 设置属性用于返回
                setPartialAttributes(competitorEntity.getSubFormData(), competitorEntity.getData(),
                        competitorEntity.getUpdateTime(), competitorEntity.getAddTime(), competitorEntity.getSerialNo(),
                        competitorEntity.getDepartmentId(), competitorEntity.getOwnerId(),
                        paasFormDataEntity, beforeUpdateVO);
                //文件柜数据保存
                saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
                //富文本数据更新
                updateFormRichText(formDataUpdateDTO, richTextData);
            }
            return new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            log.error("CompetitorFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public FormDataUpdateVO afterSave(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
                packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, beforeUpdateVO.getOldPaasFormData());
                competitorService.afterSave(saasFormSaveDTO);
                // api发起
                apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);
                // 动态添加
                saveDynamic(formDataUpdateDTO,beforeUpdateVO,updateVO);
                // 记录日志
                afterSaveLog(formDataUpdateDTO, paasFormEntity, paasFormDataEntity, oldPaasFormDataEntity, updateVO, beforeUpdateVO);
                // 数据一致性同步
                String oldCompanyName = FastJsonHelper.getStringOrDefaultFromFormData(beforeUpdateVO.getOldPaasFormData().getData(), CompetitorEnum.NAME.getAttr(), "");
                String opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntity.getData(), CompetitorEnum.NAME.getAttr(), "");
                if (!Objects.equals(oldCompanyName, opObjectName)) {
                    ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paasFormDataEntity.getCorpid(), paasFormDataEntity.getId(), opObjectName);
                    consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.COMPETITOR);
                }
                // 业务规则
                activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            } else if (Objects.equals(noApprovalRequired, 2)) {
                // 自动拒绝
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            } else {
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                paasProcessDataEntity.setFormDataId(dataId);
                paasProcessDataEntity.setBusinessType(businessType);
                paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            }
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            log.error("purchaseInvoiceFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 边境竞争对手动态添加
     * @param formDataUpdateDTO
     * @param beforeUpdateVO
     * @param updateVO
     */
    private void saveDynamic(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO){
        MainBusinessDynamicStrategy dynamicStrategy = dynamicStrategyFactory.getMainBusinessDynamicStrategy(ProjectLogEnum.COMPETITOR_UPDATE.getSubType());
        dynamicStrategy.update(new DynamicUpdateDTO(formDataUpdateDTO, beforeUpdateVO, updateVO));
    }

    @Override
    public UpdateVO updateForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        try {
            String corpid = formDataUpdateDTO.getCorpid();
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;

            CompetitorEntity competitorEntity = new CompetitorEntity();
            BeanUtil.copyProperties(paasFormDataEntity, competitorEntity);
            FormDataUtil.removeSystemData(competitorEntity.getData());
            updateLine = competitorModel.update(competitorEntity);

            // 设置属性用于返回
            setPartialAttributes(competitorEntity.getSubFormData(), competitorEntity.getData(), competitorEntity.getUpdateTime(), competitorEntity.getAddTime(), competitorEntity.getSerialNo(), competitorEntity.getDepartmentId(), competitorEntity.getOwnerId(), paasFormDataEntity, beforeUpdateVO);
            //文件柜数据保存
//                saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);


            return new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            log.error("CompetitorFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public FormDataUpdateVO afterSaveForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();

            BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
            JSONObject oldData = oldPaasFormDataEntity.getData();
            JSONObject dataList = paasFormDataEntity.getData();
            String oldSpecificationStr = updateVO.getOldSpecificationStr();
            String newSpecificationStr = updateVO.getNewSpecificationStr();
            packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, beforeUpdateVO.getOldPaasFormData());
            competitorService.afterSaveForUpdateWorkflow(saasFormSaveDTO);

            formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);

            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            log.error("CompetitorFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public Long backupData(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        return null;
    }

    @Override
    public JSONObject backupDataOtherInfo(JSONObject data, String corpid, Long dataId) {
        return data;
    }
}
